
#include "uart.h"
#include "utils.h"
#include "rf12.h"
#include "error.h"
#include "charger.h"

#define MAX_PACKET_SIZE 100
unsigned char packet[MAX_PACKET_SIZE];
#define DATA_PACKET_SIZE 50
unsigned char data_packet[DATA_PACKET_SIZE];


void RFM12B_SetTransmitMode(void);
void RFM12B_SetReceiveMode(void);


void UART_TranslateToBinaryData(unsigned char *hexdata, unsigned char hexdata_len,unsigned char  *binarydata,unsigned char *binarydata_len)
{
	*binarydata_len=0;

	for(unsigned char i=0;i<hexdata_len;i+=2)
	{
	 	binarydata[(*binarydata_len)++]=(Hex2Bin(hexdata[i])<<4)|(Hex2Bin(hexdata[i+1]));
	}
}

void UART_ProcessCommand(unsigned char *packet, unsigned char len)
{
static unsigned char data_packet_len;
static unsigned char *incoming_data;

if(len<2) return;

	switch (packet[1])
	{


		case '#': /* loopback test: [#<data in hex>] */

			UART_TranslateToBinaryData(packet+2,len-3, data_packet, &data_packet_len);

			uart_puts_P( "[#" );
				for(int i=0;i<data_packet_len;i++) uart_puthex_byte(data_packet[i]);
			uart_puts_P( "]" );

		break;

		case 's': /* send data: [s<data in hex>] */

			UART_TranslateToBinaryData(packet+2,len-3, data_packet, &data_packet_len);
			RFM12B_WritePacket(data_packet,data_packet_len);

		break;


		case 't': /* send data and wait for reply: [t<data in hex>] */

			UART_TranslateToBinaryData(packet+2,len-3, data_packet, &data_packet_len);

			if(RFM12B_SendPacketAndWaitForReply(data_packet,data_packet_len, &incoming_data ,&data_packet_len))
			{
				uart_puts_P( "[r" );
				for(int i=0;i<data_packet_len;i++) uart_puthex_byte(incoming_data[i]);
				uart_puts_P( "]" );
			}

		break;

		case 'T': /* set default to Transmit [T] */
			RFM12B_SetTransmitMode();
		break;

		case 'R': /* set default to Receive [R] */
			RFM12B_SetReceiveMode();
		break;

		case 'C': /* Get charger measures */
			GetChargerMeasures(data_packet, &data_packet_len);
			uart_puts_P( "[C" );
				for(int i=0;i<data_packet_len;i++) uart_puthex_byte(data_packet[i]);
			uart_puts_P( "]" );
		break;


		default:
			SetError(UNKNOWN_COMMAND);
			uart_puts_P( "[!" );
				for(int i=0;i<len;i++) uart_puthex_byte(packet[i]);
			uart_puts_P( "]" );

	}


}


unsigned char u_c,state=0;
unsigned int c;
unsigned char packet_h_pos=0;


void UART_Process(void)
{

	c=uart_getc();

	if(c!=UART_NO_DATA)
	{
		u_c=c&0xFF;

		if((state==0) && (u_c=='[')) state=1; // begin packet
		
		if(state==1)
		{
			packet[packet_h_pos++]=u_c;

			if(u_c==']')
			{
				UART_ProcessCommand(packet,packet_h_pos);
				packet_h_pos=0;
				state=0;
			}

			if((packet_h_pos+2)>MAX_PACKET_SIZE)
			{
				packet_h_pos=0;
				state=0;
			}
			
		}
	}

}
